// pages/admin-products/admin-products.js
const { apiService } = require('../../utils/api')
const { showSuccess, showError, showLoading, hideLoading } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    products: [],
    loading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10,
    searchKeyword: '',
    statusFilter: -1, // -1: 全部, 0: 下架, 1: 上架
    statusOptions: [
      { value: -1, label: '全部状态' },
      { value: 0, label: '下架' },
      { value: 1, label: '上架' }
    ],
    showAddModal: false,
    showEditModal: false,
    currentProduct: null,
    formData: {
      name: '',
      description: '',
      price: '',
      imageUrl: '',
      specifications: '',
      materials: '',
      difficulty: 1,
      timeRequired: '',
      quantity: 1
    },
    difficultyOptions: [
      { value: 1, label: '简单' },
      { value: 2, label: '中等' },
      { value: 3, label: '困难' },
      { value: 4, label: '专家' },
      { value: 5, label: '大师' }
    ],
    totalProducts: 0,
    onlineProducts: 0,
    todayProducts: 0,
    statsLoading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadProductsStats()
    this.loadProducts()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadProducts()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshProducts()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMoreProducts()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '产品管理',
      path: '/pages/admin-products/admin-products'
    }
  },

  /**
   * 加载产品统计数据
   */
  loadProductsStats: function() {
    this.setData({ statsLoading: true })

    apiService.getProductsStats()
      .then((stats) => {
        this.setData({
          totalProducts: stats.total || 0,
          onlineProducts: stats.online || 0,
          todayProducts: stats.today || 0,
          statsLoading: false
        })
      })
      .catch((error) => {
        console.error('加载产品统计失败:', error)
        this.setData({ statsLoading: false })
      })
  },

  /**
   * 加载产品列表
   */
  loadProducts: function() {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      keyword: this.data.searchKeyword,
      status: this.data.statusFilter === -1 ? null : this.data.statusFilter
    }

    apiService.getProductsList(params)
      .then((result) => {
        const newProducts = result.list || []
        const products = this.data.pageNum === 1 ? newProducts : [...this.data.products, ...newProducts]

        this.setData({
          products: products,
          hasMore: newProducts.length === this.data.pageSize,
          loading: false
        })
      })
      .catch((error) => {
        this.setData({ loading: false })
        showError(error.message || '加载产品列表失败')
      })
  },

  /**
   * 刷新产品列表
   */
  refreshProducts: function() {
    this.setData({
      products: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadProducts()
    this.loadProductsStats()
  },

  /**
   * 加载更多产品
   */
  loadMoreProducts: function() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({
      pageNum: this.data.pageNum + 1
    })
    this.loadProducts()
  },

  /**
   * 搜索输入处理
   */
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  /**
   * 执行搜索
   */
  onSearch: function() {
    this.refreshProducts()
  },

  /**
   * 清空搜索
   */
  onClearSearch: function() {
    this.setData({
      searchKeyword: ''
    })
    this.refreshProducts()
  },

  /**
   * 状态筛选变化
   */
  onStatusFilterChange: function(e) {
    const value = parseInt(e.detail.value)
    this.setData({
      statusFilter: value
    })
    this.refreshProducts()
  },

  /**
   * 显示添加产品弹窗
   */
  showAddProduct: function() {
    this.setData({
      showAddModal: true,
      formData: {
        name: '',
        description: '',
        price: '',
        imageUrl: '',
        specifications: '',
        materials: '',
        difficulty: 1,
        timeRequired: '',
        quantity: 1
      }
    })
  },

  /**
   * 隐藏添加产品弹窗
   */
  hideAddProduct: function() {
    this.setData({
      showAddModal: false
    })
  },

  /**
   * 显示编辑产品弹窗
   */
  showEditProduct: function(e) {
    const productId = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === productId)

    if (product) {
      this.setData({
        showEditModal: true,
        currentProduct: product,
        formData: {
          name: product.name || '',
          description: product.description || '',
          price: product.price || '',
          imageUrl: product.imageUrl || '',
          specifications: product.specifications || '',
          materials: product.materials || '',
          difficulty: product.difficulty || 1,
          timeRequired: product.timeRequired || '',
          quantity: product.quantity || 1
        }
      })
    }
  },

  /**
   * 隐藏编辑产品弹窗
   */
  hideEditProduct: function() {
    this.setData({
      showEditModal: false,
      currentProduct: null
    })
  },

  /**
   * 表单输入处理
   */
  onFormInput: function(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value

    this.setData({
      ['formData.' + field]: value
    })
  },

  /**
   * 难度选择变化
   */
  onDifficultyChange: function(e) {
    const value = parseInt(e.detail.value)
    this.setData({
      'formData.difficulty': value
    })
  },

  /**
   * 选择图片
   */
  chooseImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (res.tempFilePaths.length > 0) {
          this.uploadImage(res.tempFilePaths[0])
        }
      },
      fail: (error) => {
        showError('选择图片失败')
      }
    })
  },

  /**
   * 上传图片
   */
  uploadImage: function(filePath) {
    showLoading('上传中...')

    // 这里应该调用后端的上传接口
    // 现在暂时使用本地路径
    this.setData({
      'formData.imageUrl': filePath
    })
    hideLoading()
    showSuccess('图片上传成功')
  },

  /**
   * 创建产品
   */
  createProduct: function() {
    const { formData } = this.data

    if (!formData.name.trim()) {
      showError('请输入产品名称')
      return
    }

    if (!formData.price || parseFloat(formData.price) <= 0) {
      showError('请输入有效的产品价格')
      return
    }

    if (!formData.imageUrl) {
      showError('请选择产品图片')
      return
    }

    showLoading('创建中...')

    apiService.createProduct(formData)
      .then(() => {
        hideLoading()
        showSuccess('产品创建成功')
        this.hideAddProduct()
        this.refreshProducts()
      })
      .catch((error) => {
        hideLoading()
        showError(error.message || '创建产品失败')
      })
  },

  /**
   * 更新产品
   */
  updateProduct: function() {
    const { currentProduct, formData } = this.data

    if (!currentProduct) return

    if (!formData.name.trim()) {
      showError('请输入产品名称')
      return
    }

    if (!formData.price || parseFloat(formData.price) <= 0) {
      showError('请输入有效的产品价格')
      return
    }

    if (!formData.imageUrl) {
      showError('请选择产品图片')
      return
    }

    showLoading('更新中...')

    apiService.updateProduct(currentProduct.id, formData)
      .then(() => {
        hideLoading()
        showSuccess('产品更新成功')
        this.hideEditProduct()
        this.refreshProducts()
      })
      .catch((error) => {
        hideLoading()
        showError(error.message || '更新产品失败')
      })
  },

  /**
   * 上架产品
   */
  onlineProduct: function(e) {
    const productId = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === productId)

    if (!product) return

    showLoading('上架中...')

    apiService.onlineProduct(productId)
      .then(() => {
        hideLoading()
        showSuccess('产品上架成功')
        this.refreshProducts()
      })
      .catch((error) => {
        hideLoading()
        showError(error.message || '上架产品失败')
      })
  },

  /**
   * 下架产品
   */
  offlineProduct: function(e) {
    const productId = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === productId)

    if (!product) return

    wx.showModal({
      title: '确认下架',
      content: `确定要下架产品"${product.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          showLoading('下架中...')

          apiService.offlineProduct(productId)
            .then(() => {
              hideLoading()
              showSuccess('产品下架成功')
              this.refreshProducts()
            })
            .catch((error) => {
              hideLoading()
              showError(error.message || '下架产品失败')
            })
        }
      }
    })
  },

  /**
   * 删除产品
   */
  deleteProduct: function(e) {
    const productId = e.currentTarget.dataset.id
    const product = this.data.products.find(p => p.id === productId)

    if (!product) return

    wx.showModal({
      title: '确认删除',
      content: `确定要删除产品"${product.name}"吗？此操作不可恢复！`,
      success: (res) => {
        if (res.confirm) {
          showLoading('删除中...')

          apiService.deleteProduct(productId)
            .then(() => {
              hideLoading()
              showSuccess('产品删除成功')
              this.refreshProducts()
            })
            .catch((error) => {
              hideLoading()
              showError(error.message || '删除产品失败')
            })
        }
      }
    })
  },

  /**
   * 获取状态文本
   */
  getStatusText: function(status) {
    const statusMap = {
      0: '下架',
      1: '上架'
    }
    return statusMap[status] || '未知'
  },

  /**
   * 获取状态样式类
   */
  getStatusClass: function(status) {
    const classMap = {
      0: 'status-offline',
      1: 'status-online'
    }
    return classMap[status] || ''
  },

  /**
   * 获取难度文本
   */
  getDifficultyText: function(difficulty) {
    const difficultyMap = {
      1: '简单',
      2: '中等',
      3: '困难',
      4: '专家',
      5: '大师'
    }
    return difficultyMap[difficulty] || '未知'
  }
})

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})